package Protobuf;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

public class ProtoClient {
	public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException {
		Socket serverSocket = new Socket("localhost", 90);
    	InputStream input = serverSocket.getInputStream();
    	OutputStream output = serverSocket.getOutputStream();
    	int j;
    	SensorData initialData;
    	long time = System.currentTimeMillis();
    	for (int i = 0; i < 10000; i++) {
            initialData = SensorData.generate();
        	SensorDataProto.SensorData.Builder data = SensorDataProto.SensorData.newBuilder();
        	data.setLatitude(initialData.getLatitude());
        	data.setLongitude(initialData.getLongitude());
        	data.setTemperature(initialData.getTemperature());
        	data.setElevation(initialData.getDepth());
        	data.build().writeDelimitedTo(output);
        	j = input.read();
    		while (j == (-1)) {
    			Thread.sleep(5);
    			j = input.read();
    		}
    	}
    	System.out.println("throughput = "+1d * (System.currentTimeMillis() - time)/10000);
    	initialData = SensorData.generate();
    	SensorDataProto.SensorData.Builder data = SensorDataProto.SensorData.newBuilder();
    	data.setLatitude(initialData.getLatitude());
    	data.setLongitude(initialData.getLongitude());
    	data.setTemperature(initialData.getTemperature());
    	data.setElevation(initialData.getDepth());

    	long timeDelay = System.currentTimeMillis();
    	data.build().writeDelimitedTo(output);
    	j = input.read();
		while (j == (-1)) {
			Thread.sleep(5);
			j = input.read();
		}
		System.out.println("delay = "+1d*(System.currentTimeMillis() - timeDelay));
		input.close();
		output.close();
    	serverSocket.close();
	}
}
